/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package aeduserver;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

/**
 *
 * @author Adrian Hostettler
 */
class NameServerConn
        implements Runnable{

    /**
     * Playername of connected Client.
     */
    private String playerName = "";
    private int playerId = 0;
    /**
     * Socket fuer Clientverbindung
     */
    private Socket s;
    /**
     * Eingabestrom vom Client
     */
    private BufferedReader vomClient;
    /**
     * Ausgabestrom zum Client
     */
    private PrintWriter zumClient;

    /**
     * Konstruktor, baut Ueberwachungsmechanismus und Datenstroeme zum/vom
     * Client auf.
     *
     * @param s Socket fuer Clientverbindung.
     * @param playerId id für Player.
     */
    public NameServerConn(Socket s, int playerId) {
        this.s = s;
        this.playerId = playerId;

        try {
            vomClient = new BufferedReader(new InputStreamReader(s.getInputStream()));
            zumClient = new PrintWriter(s.getOutputStream(), true);
            this.run();
        } catch (Exception e) {
            System.out.println(e);
        }
    }

    /**
     * Interaktion, liest und verarbeitet Nachrichten vom Client.
     */
    @Override
    public void run() {
        System.out.println("waiting for name");
        try {
            this.playerName = vomClient.readLine();
            zumClient.println(playerId);
        } catch (Exception e) {
            System.out.println("\nVerbindung zum Client unterbrochen\n  " + e);
            release();
        }
    }

    /**
     * Schliesst Verbindung zum Client, setzt Model zurueck.
     */
    public void release() {
        System.out.println("Protokoll fuer Client beendet");
        try {
            s.close();
        } catch (Exception e) {
            System.out.println("\nFehler beim Schliessen des Clientprotokoll\n "
                    + e);
        }
    }

    boolean hasNoName() {
        if (this.playerName.equals("")) {
            return true;
        } else {
            return false;
        }
    }

    String getPlayerName() {
        return this.playerName;
    }
    int getPlayerId(){
        return this.playerId;
    }
}